import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score

wine = datasets.load_wine()
features, labels = wine.data, wine.target
kernel_functions = ['linear', 'poly', 'rbf', 'sigmoid']
colors = [(0.1, 0.1, 1, 0.5), (0.1, 1, 0.1, 0.5), (1, 0.1, 0.1, 0.5), (0.5, 0.1, 0.5, 0.5)]
accuracies = []

if __name__ == '__main__':
    features_train, features_test, labels_train, labels_test = train_test_split(features, labels, test_size=0.2,
                                                                                random_state=42)
    for kernel in kernel_functions:
        svm_model = SVC(kernel=kernel)
        svm_model.fit(features_train, labels_train)
        labels_test_predict = svm_model.predict(features_test)
        accuracy = accuracy_score(labels_test_predict, labels_test)
        accuracies.append(accuracy)
        print(f"核函数: {kernel}, 分类精度: {accuracy}")

    # Plotting
    plt.figure(figsize=(8, 6))
    bars = plt.bar(kernel_functions, accuracies, color=colors)
    plt.xlabel('Kernel Function')
    plt.ylabel('Accuracy')
    plt.title('Accuracy of SVM with Different Kernel Functions')
    plt.ylim(0, 1)
    plt.grid(axis='y', linestyle='--', alpha=0.7)
    legend_labels = [f'{kernel} ({accuracy:.2f})' for kernel, accuracy in zip(kernel_functions, accuracies)]
    plt.legend(bars, legend_labels)
    plt.show()
